<template>
  <div :id="idTime" :style="{ width: '100%', height: height + 'px' }"></div>
</template>

<script lang="ts" setup>
/*
用于显示跟速度相关图形再适合不过。

## API

### pie

| 参数 | 说明 | 类型 | 默认值 |
|----|----|----|-----|
| `[repaint]` | 数据再次变更时是否重绘 | `boolean` | `true` |
| `[delay]` | 延迟渲染，单位：毫秒 | `number` | `0` |
| `[animate]` | 是否显示动画 | `boolean` | `true` |
| `[color]` | 图表颜色 | `string` | `rgba(24, 144, 255, 0.85)` |
| `[height]` | 图表高度 | `number` | - |
| `[hasLegend]` | 是否显示 legend | `boolean` | `false` |
| `[padding]` | 图表内部间距 | `number[]` | `[12, 0, 12, 0]` |
| `[percent]` | 占比 | `number` | - |
| `[lineWidth]` | 边框粗细 | `number` | `0` |
| `[inner]` | 内部极坐标系的半径 | `number` | `0.75` |
| `[blockMaxWidth]` | 多少宽度为块显示 | `number` | `380` |
| `[tooltip]` | 是否显示 tooltip | `boolean` | `true` |
| `[subTitle]` | 图表子标题 | `string,TemplateRef<void><void>` | - |
| `[total]` | 总量 | `string,number,TemplateRef<void><void>` | - |
| `[valueFormat]` | y轴格式化 | `(y: number) => string` | - |
| `[data]` | 数据 | `v2PieData[]` | - |
| `[colors]` | 颜色列表 | `string[]` | - |
| `[interaction]` | 交互类型，none 无 element-active 图形元素，active-region 图表组件，brush 框选，drag-move 移动 | `InteractionType` | `none` |
| `[ratio]` | 百分比配置项 | `G2PieRatio` | `{ text: '占比', inverse: '反比', color: '', inverseColor: '#F0F2F5' }` |
| `(clickItem)` | 点击项回调 | `EventEmitter<G2PieClickItem>` | - |
| `[tooltipType]` | Tooltip显示类型 | `'mini','default'` | `'default'` |
### v2PieData

| 参数 | 说明 | 类型 | 默认值 |
|----|----|----|-----|
| `[x]` | x轴 | `Array<string | number>` | - |
| `[y]` | y轴 | `Array<string | number | {value: string | number,itemStyle: color}>` | - |
| `[color]` | 轴颜色 | `string` | - |

*/

import { Item } from "ant-design-vue/lib/menu";
import * as echarts from "echarts";
import { defineProps, defineEmits, onMounted, onUnmounted, watch, ref } from "vue";
import { number } from "vue-types";

const Emits = defineEmits(["clickItem"]);

const props = defineProps({
  //颜色列表
  colors: {
    type: Array,
    default: [
      "#f36c6d",
      "#fa8a49",
      "#828bf5",
      "#54a9f6",
      "#31c7b0",
      "#71c731",
      "#5470c6",
      "#91cc75",
      "#fac858",
      "#ee6666",
      "#73c0de",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc",
    ],
  },
  repaint: {
    type: Boolean,
    default: true,
  },
  delay: {
    type: Number,
    default: 0,
  },
  color: {
    type: String,
    default: "rgba(24, 144, 255, 0.2)",
  },
  //图表高度
  height: {
    type: Number,
    default: 44,
  },
  //是否显示图例 legend
  hasLegend: {
    type: Boolean,
    default: false,
  },
  //边框粗细  默认半径的88%
  lineWidth: {
    type: Number,
    default: null,
  },
  //内部极坐标系的半径
  inner: {
    type: Number,
    default: 44,
  },
  //饼图图形上的文本标签
  label: {
    type: Boolean,
    default: true,
  },
  //是否显示提示框
  tooltip: {
    type: Boolean,
    default: true,
  },
  //标题
  title: {
    type: String,
    default: "",
  },
  //图表子标题
  subTitle: {
    type: String,
    default: "",
  },
  animate: {
    type: Boolean,
    default: true,
  },
  padding: {
    type: Array,
    default: [0, 0, 0, 0],
  },
  //数据
  data: {
    type: Object,
    default: null,
  },
  //总量
  total: {},
  tooltipType: {
    type: String,
    default: "default",
  },
});

const myChart = ref(null);

//生成 图表 id
let idTime = "ec_" + String(new Date().getTime());

//销毁组件取消监听
onUnmounted(() => {
  removeEventListener("resize", v2Areathrottle, false);
});

if (props.repaint) {
  watch(
    () => props.data,
    (data, predata) => {
      if (predata != null) {
        reload(data);
      } else {
        chartInit();
      }
    },
    { deep: true }
  );
}

//防抖函数
const v2Areathrottle: any = function (fn: any, wait: any) {
  let timer: any = null;
  return function () {
    let context = {};
    let args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        fn.apply(context, args);
        timer = null;
      }, wait);
    }
  };
};

//刷新数据
const reload = (data: any) => {
  const option = myChart.value.getOption();
  //数据重组
  let arrpie: Array<{ name: any; value: any }> = [];
  data.x.forEach((res: any, index: any) => {
    let json = { name: null, value: null };
    json.name = res;
    json.value = props.data.y[index];
    arrpie.push(json);
  });
  option.series[0].data = data[0].y;
  myChart.value.setOption(option);
};

//渲染
const v2MiniPie = () => {

  let myChart = echarts.init(document.getElementById(idTime) as HTMLElement);
  let option: any;
  //数据重组
  let arrpie: Array<{ name: any; value: any }> = [];
  props.data.x.forEach((res: any, index: any) => {
    let json = { name: null, value: null };
    json.name = res;
    json.value = props.data.y[index];
    arrpie.push(json);
  });
  option = {
    //图例
    legend: {
      show: props.hasLegend,
      type: "scroll",
      orient: "vertical",
      right: 20,
      top: "10",
      data: arrpie,
      selected: arrpie,
    },
    tooltip: {
      show: props.tooltip,
      trigger: "item",
      formatter: "{b} : {c} ({d}%)",
    },
    title: {
      show: props.title == "" ? false : true,
      text: props.title,
      textStyle: {
        color: "#999999",
        fontWeight: "normal",
        fontSize: "14",
      },
    },
    itemStyle: {
      color: props.color,
    },
    color: props.colors,
    animation: props.animate,
    animationDelay: props.delay,
    series: [
      {
        left: props.padding[0],
        top: props.padding[1],
        right: props.padding[2],
        bottom: props.padding[3],
        radius: [props.inner, props.lineWidth == null ? "88%" : props.lineWidth],
        tooltip: {
          //是否显示提示框组件
          show: props.tooltip,
          showContent: true,
        },
        label: {
          show: props.subTitle ? true : props.label,
          position: props.subTitle ? "center" : "outside",
          formatter: function (params: any) {
            const label = `${props.subTitle}:${props.total}`;
            return label;
          },
          fontSize: "14px",
        },
        data: arrpie,
        type: "pie",
      },
    ],
  };

  myChart.setOption(option);
  //屏幕自适应
  window.addEventListener(
    "resize",
    v2Areathrottle(() => {
      myChart.resize();
    }, 200)
  );
  myChart.on("click", function (params) {
    Emits("clickItem", params);
  });

  return myChart;
};
let chartInit = () => {
  if (myChart.value != null) return;

  myChart.value = v2MiniPie();
};
</script>
<script lang="ts">
export default {
  name: "pie",
};
</script>
<style lang="less" scoped></style>
